IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[InsertCuenta]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[InsertCuenta]
GO

CREATE PROCEDURE [dbo].[InsertCuenta]
(
	@IdCuenta int OUT,
	@IdBanco int,
	@Numero varchar(50),
	@Tipo tinyint
)
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @ID int
	SET @ID = ISNULL((SELECT IdCuenta FROM [Cuenta] WHERE [IdBanco] = @IdBanco AND [Numero] = @Numero), 0)
	
	IF @ID = 0
		BEGIN
			INSERT INTO [Cuenta] ([IdBanco], [Numero], [Tipo]) VALUES (@IdBanco, @Numero, @Tipo)
			SET @IdCuenta = SCOPE_IDENTITY()
		END
	ELSE 
		BEGIN
			EXEC dbo.UpdateCuenta @ID, @IdBanco, @Numero, @Tipo;
			SET @IdCuenta = @ID
		END

	SET NOCOUNT OFF
END

GO
